<template>
  <div class="address">
      <scroll-view scroll-y="true" class="content" style="height: 100%">
        <div class="item" v-if="listData.length !== 0">
            <div v-for="(item,index) in listData" :key="index">
                <div class="list">
                    <div>
                        <span>{{item.name}}</span>
                        <div class="default" v-if="item.is_default">默认</div>
                    </div>
                    <div class="info" @click="selAddress(item.id)">
                        <p>{{item.mobile}}</p>
                        <p>{{item.address+item.address_detail}}</p>
                    </div>
                    <div @click="toDetail(item.id)"></div>
                </div>
            </div>
        </div>

        <!-- 没有地址时 -->
        <div class="center" v-else>
            <p>收货地址失踪了~</p>
        </div>
      </scroll-view>

      <div class="footer">
          <div @click="wxaddress(1)">+ 新建地址</div>
          <div @click="wxaddress">一键导入微信地址</div>
      </div>
  </div>
</template>

<script>
import { get, getStorageOpenid } from '../../utils'
export default {
    data() {
        return {
            listData: [],
            openId: ''
        }
    },
    onShow() {
        this.openId = getStorageOpenid()
        this.getAddressList()
    },
    methods: {
        toDetail(id) {
            wx.navigateTo({
                url: '/pages/addaddress/main?id=' + id
            })
            // console.log(id)
        },
        wxaddress(index) {
            if(index === 1) {
                wx.navigateTo({
                    url: '/pages/addaddress/main'
                })
            } else {
                // 微信小程序原生的wx.chooseAddress()获取用户收货地址
                wx.chooseAddress({
                    success(res) {
                        // consol   e.log(res)
                        // 将获取到的数据进行解析
                        let result = encodeURIComponent(JSON.stringify(res));
                        wx.navigateTo({
                            url: '/pages/addaddress/main?res=' + result
                        })
                    }
                })
            }
        },
        async getAddressList() {
            const data = await get('/address/getListAction', {
                openId: this.openId
            })
            // console.log(data)
            this.listData = data.addressList
            // console.log(this.listData)
        },
        selAddress(id) {
            // 将当前地址信息的id存入本地
            wx.setStorageSync('addressId', id)
            wx.navigateback({
                delta: 1
            })
        }
    }
}
</script>

<style scoped>
@import './style.css';
</style>